package com.awen.config;
import com.awen.pojo.Configuration;
import com.awen.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import java.io.InputStream;
import java.util.List;
public class XMlMapperBuilder {
    private Configuration configuration;
    public XMlMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }
    public void parse(InputStream inputStream) throws DocumentException {
        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();
        String namespace = rootElement.attributeValue("namespace");
        List<Element> list = rootElement.selectNodes("//select");
        fullMappedStatementMap(namespace, list);
        List selectUpdate = rootElement.selectNodes("//update");
        fullMappedStatementMap(namespace,selectUpdate);
        List selectDelete = rootElement.selectNodes("//delete");
        fullMappedStatementMap(namespace,selectDelete);
        List selectInsert = rootElement.selectNodes("//insert");
        fullMappedStatementMap(namespace,selectInsert);
    }
    //填充到MappedStatementMap
    private void fullMappedStatementMap(String namespace, List<Element> list) {
        for (Element element : list) {
            String id = element.attributeValue("id");
            String resultType = element.attributeValue("resultType");
            String paramterType = element.attributeValue("paramterType");
            String sqlText = element.getTextTrim();
            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setId(id);
            mappedStatement.setResultType(resultType);
            mappedStatement.setParamterType(paramterType);
            mappedStatement.setSql(sqlText);
            String key = namespace + "." + id;
            configuration.getMappedStatementMap().put(key, mappedStatement);
        }
    }
}
